<template>
  <div class="category-list-container">
    <div class="page-header">
      <h2>分类管理</h2>
      <el-button type="primary" @click="openAddDialog">新增分类</el-button>
    </div>

    <!-- 搜索 -->
    <div class="search-filter">
      <el-input
        v-model="searchName"
        placeholder="请输入分类名称"
        style="width: 200px; margin-right: 10px;"
        clearable
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 分类列表 -->
    <el-table :data="categoryList.records" style="width: 100%" v-loading="loading">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="分类ID" width="80" />
      <el-table-column prop="name" label="分类名称" width="150" />
      <el-table-column prop="description" label="分类描述" :show-overflow-tooltip="true" />
      <el-table-column prop="sortOrder" label="排序" width="100">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.sortOrder"
            :min="0"
            :max="1000"
            @change="handleSortChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="categoryList.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        label-width="100px"
        style="max-width: 400px;"
      >
        <el-form-item label="分类名称" prop="name" :rules="[{ required: true, message: '请输入分类名称', trigger: 'blur' }]">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        
        <el-form-item label="分类描述" prop="description">
          <el-input v-model="categoryForm.description" type="textarea" placeholder="请输入分类描述" />
        </el-form-item>
        
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number
            v-model="categoryForm.sortOrder"
            :min="0"
            :max="1000"
            placeholder="请输入排序号"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

// 表格数据
const categoryList = ref({ records: [], total: 0 });
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索
const searchName = ref('');

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('新增分类');
const categoryFormRef = ref();
const categoryForm = reactive({
  id: null,
  name: '',
  description: '',
  sortOrder: 0
});

// 加载分类列表
const loadCategoryList = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      name: searchName.value || undefined
    };
    const res = await axios.get('/api/category', { params });
    if (res.data.code === 200 && res.data.data) {
      categoryList.value = res.data.data;
    }
  } catch (error) {
    ElMessage.error('加载分类列表失败');
    console.error('加载分类列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadCategoryList();
};

// 重置搜索
const resetSearch = () => {
  searchName.value = '';
  currentPage.value = 1;
  loadCategoryList();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  loadCategoryList();
};

// 当前页变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  loadCategoryList();
};

// 打开新增对话框
const openAddDialog = () => {
  dialogTitle.value = '新增分类';
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = async (row: any) => {
  dialogTitle.value = '编辑分类';
  try {
    const res = await axios.get(`/api/category/${row.id}`);
    if (res.data.code === 200 && res.data.data) {
      Object.assign(categoryForm, res.data.data);
      dialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error('加载分类详情失败');
    console.error('加载分类详情失败:', error);
  }
};

// 重置表单
const resetForm = () => {
  categoryForm.id = null;
  categoryForm.name = '';
  categoryForm.description = '';
  categoryForm.sortOrder = 0;
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields();
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!categoryFormRef.value) return;
  
  try {
    await categoryFormRef.value.validate();
    
    if (categoryForm.id) {
      // 编辑分类
      const res = await axios.put('/api/category', categoryForm);
      if (res.data.code === 200) {
        ElMessage.success('修改成功');
        dialogVisible.value = false;
        loadCategoryList();
      }
    } else {
      // 新增分类
      const res = await axios.post('/api/category', categoryForm);
      if (res.data.code === 200) {
        ElMessage.success('新增成功');
        dialogVisible.value = false;
        loadCategoryList();
      }
    }
  } catch (error) {
    console.error('提交表单失败:', error);
  }
};

// 删除分类
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个分类吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const res = await axios.delete(`/api/category?idList=${id}`);
    if (res.data.code === 200) {
      ElMessage.success('删除成功');
      loadCategoryList();
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
      console.error('删除失败:', error);
    }
  }
};

// 排序改变
const handleSortChange = async (row: any) => {
  try {
    await axios.put('/api/category', {
      id: row.id,
      sortOrder: row.sortOrder
    });
    ElMessage.success('排序修改成功');
  } catch (error) {
    ElMessage.error('排序修改失败');
    console.error('排序修改失败:', error);
    // 重新加载列表以恢复正确的排序
    loadCategoryList();
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadCategoryList();
});
</script>

<style scoped>
.category-list-container {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.search-filter {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>